﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Security.Cryptography;
using System.Text;

public partial class Registration : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void btnRegis_Click(object sender, EventArgs e)
    {
        Sharemp3DataContext db = new Sharemp3DataContext();

        string loginName = txtLoginName.Text;
        string email = txtEmail.Text;

        int n = db.UserLogins.Where(i => i.Username == loginName).Count();

        if (n == 0)
        {
            string fullname = txtFullName.Text;
            string pass = txtPass.Text;
            string passHash;
            using (MD5 md5Hash = MD5.Create())
            {
                passHash = GetMd5Hash(md5Hash, pass);
            }

            UserLogin user1 = new UserLogin() { Username = loginName, Password = passHash, Name = fullname, EmailAddress = email, Role = 2 };

            try
            {
                db.UserLogins.InsertOnSubmit(user1);
                db.SubmitChanges();
                lblResult.Text = "Registration successful !";
            }
            catch
            {
                lblResult.Text = "Registration is fail";
            }
        }
        else
        {
            lblResult.Text = "Username or email is existed !";
        }
    }

    private string GetMd5Hash(MD5 md5Hash, string input)
    {
        byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(input));
        StringBuilder sbuilder = new StringBuilder();
        for (int i = 0; i < data.Length; i++)
        {
            sbuilder.Append(data[i].ToString("x2"));
        }
        return sbuilder.ToString();
    }        
}